<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\goods\model;

use app\admin\model\RouteModel;
use think\Model;
use think\Db;
use app\goods\model\PortalPostModel;

class GoodsModel extends Model
{

    protected $type = [
        'more' => 'array',
    ];

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    /**
     * 关联 user表
     * @return $this
     */
    public function user()
    {
        return $this->belongsTo('UserModel', 'user_id')->setEagerlyType(1);
    }

    /**
     * 关联分类表
     */
    public function categories()
    {
        return $this->belongsToMany('GoodsCategoryModel', 'goods_category_relate', 'category_id', 'goods_id');
    }

    /**
     * 标题敏感词过滤
     * @param $value
     * @return false|int
     */
    public function setGoodsNameAttr($value)
    {
        return cmf_replaceSensitive($value);
    }

    /**
     * post_content 自动转化
     * @param $value
     * @return string
     */
    public function getPostExcerptAttr($value)
    {   
        return cmf_replace_content_file_url(htmlspecialchars_decode($value));
    }
    
    public function setPostExcerptAttr($value)
    {
        $value = cmf_replaceSensitive($value);
        
        return htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($value), true));
    }
    
    /**
     * post_content 自动转化
     * @param $value
     * @return string
     */
    public function getPostContentAttr($value)
    {   
        return cmf_replace_content_file_url(htmlspecialchars_decode($value));
    }

    /**
     * post_content 自动转化
     * @param $value
     * @return string
     */
    public function setPostContentAttr($value)
    {
        $value = cmf_replaceSensitive($value);
        
        return htmlspecialchars(cmf_replace_content_file_url(htmlspecialchars_decode($value), true));
    }

    /**
     * 页面标题敏感词过滤
     * @param $value
     * @return false|int
     */
    public function setPageTitleAttr($value)
    {
        return cmf_replaceSensitive($value);
    }

    /**
     * 页面关键字敏感词过滤
     * @param $value
     * @return false|int
     */
    public function setPageKeywordsAttr($value)
    {
        return cmf_replaceSensitive($value);
    }

    /**
     * 页面描述敏感词过滤
     * @param $value
     * @return false|int
     */
    public function setPageDescriptionAttr($value)
    {
        return cmf_replaceSensitive($value);
    }
    
    /**
     * published_time 自动完成
     * @param $value
     * @return false|int
     */
    public function setPublishedTimeAttr($value)
    {
        return strtotime($value);
    }

    /**
     * 后台管理添加产品
     * @param array $data 产品数据
     * @param array|string $categories 产品分类 id
     * @return $this
     */
    public function adminAddGoods($data, $categories, $param=[])
    {
        $data['site_id'] = get_site_id();
        $data['user_id'] = cmf_get_current_admin_id();
        
        if (!empty($data['more']['thumbnail'])) {
            $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
        }

        if (is_string($categories)) {
            $categories = explode(',', $categories);
        }

        //不需要审核的情况，为超级管理员所添加的或者文章所属分类不需要审核流程
        $audit_id = get_audit_id($categories, 'goods_category');
        if( !empty($audit_id) ){
            $auditStatus = db('audit_flow')->value('status');
        }
        if( session('ROLE_ID') == 1 || empty($audit_id) || empty($auditStatus) ){
            $data['post_status'] = 99;
        }

        $this->allowField(true)->data($data, true)->isUpdate(false)->save();

        $this->categories()->save($categories);

        //排序号，按每个文类下产品的最大序号+1
        foreach ($categories as $k => $v) {
            //当前分类下产品的最大排序号
            $maxListOrder  = db('goods_category_relate')
                          -> where('category_id',$v)
                          -> max('list_order');
            //最大排序号+1
            $maxListOrder += 1;     
            //更新的条件
            $where = [
                'goods_id'     => $this->goods_id,
                'category_id' => $v,
            ];
            //更新新增文章的排序号
            db('goods_category_relate')->where($where)->update(['list_order'=>$maxListOrder]);
        }

        //处理产品属性
        $this->_handleSpec($this->goods_id, $param);

        return $this;

    }

    /**
     * 后台管理编辑产品
     * @param array $data 产品数据
     * @param array|string $categories 产品分类 id
     * @return $this
     */
    public function adminEditGoods($data, $categories, $param=[])
    {
        //旧数据
        // $goodsPostModel = new PortalPostModel();
        // $old_data = Db::name('PortalPost')->field('file_url,more')->find($data['id']);
        $old_data = $this->field('more')->find($data['goods_id']);
        unset($data['user_id']);

        if (!empty($data['more']['thumbnail'])) {
            $data['more']['thumbnail'] = cmf_asset_relative_url($data['more']['thumbnail']);
        }

        // $data['post_status']    = empty($data['post_status']) ? 0 : 1;
        $data['is_top']         = empty($data['is_top']) ? 0 : 1;
        $data['recommended']    = empty($data['recommended']) ? 0 : 1;
        $data['more']['layout'] = empty($data['more']['layout']) ? 1 : $data['more']['layout'];

        $this->allowField(true)->isUpdate(true)->data($data, true)->save();

        if (is_string($categories)) {
            $categories = explode(',', $categories);
        }

        $oldCategoryIds        = $this->categories()->column('category_id');
        $sameCategoryIds       = array_intersect($categories, $oldCategoryIds);
        $needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
        $newCategoryIds        = array_diff($categories, $sameCategoryIds);

        if (!empty($needDeleteCategoryIds)) {
            $this->categories()->detach($needDeleteCategoryIds);
        }

        if (!empty($newCategoryIds)) {
            $this->categories()->attach(array_values($newCategoryIds));
        }

        //处理产品属性
        $this->_handleSpec($data['goods_id'], $param);

        // //删除缩略图
        // if( !empty($old_data['more']['thumbnail']) ){
        //     if( $data['more']['thumbnail'] != $old_data['more']['thumbnail'] ){
        //         del_file($old_data['more']['thumbnail']);//删除文件
        //     }
        // }

        // //删除大缩略图
        // if( !empty($old_data['more']['search_thumb']) ){
        //     if( $data['more']['search_thumb'] != $old_data['more']['search_thumb'] ){
        //         del_file($old_data['more']['search_thumb']);//删除文件
        //     }
        // }

        // //旧相册
        // if( !empty($old_data['more']['photos']) ){
        //     if( !empty($data['more']['photos']) ){
        //         foreach ($data['more']['photos'] as $k => $v) {
        //             $new_photos_url[] = $v['url'];
        //         }
        //     }
        //     foreach ($old_data['more']['photos'] as $k => $v) {
        //         $old_photos_url[] = $v['url'];
        //     }
        //     //若新相册为空，则删除所有旧相册图片，否则根据差集进行删除
        //     if( empty($new_photos_url) ){
        //         $del_photo_url = $old_photos_url;
        //     }else {
        //         //若图片在旧相册存在，在新相册不存在，则说明该图片已移除，进行删除图片文件
        //         $del_photo_url = array_diff($old_photos_url, $new_photos_url);
        //     }
        //     foreach ($del_photo_url as $k => $v) {
        //         del_file($v);//删除文件
        //     }
        // }

        return $this;

    }

    

    private function _handleSpec($goods_id, $data=array()){
        /* 处理属性 */
        // $data            = $this->request->param();
        // $data            = $this->request->param();
        $attr_id_list    = $data['attr_id_list'];
        $attr_value_list = $data['attr_value_list'];

        if ( !empty($attr_id_list) && !empty($attr_value_list) ) {
            // 取得原有的属性值
            $goods_attr_list = array();

            $res = db('goodsAttr')
                -> alias('g')
                -> field('g.*, a.attr_type')
                -> join('__GOODS_ATTRIBUTE__ a', 'a.attr_id = g.attr_id', 'LEFT')
                -> where("g.goods_id = '$goods_id'")
                -> select();

            foreach ($res as $k => $v) {
                $goods_attr_list[$v['attr_id']][$v['attr_value']] = array('sign' => 'delete', 'goods_attr_id' => $v['goods_attr_id']);
            }
            
            // 循环现有的，根据原有的做相应处理
            if(isset($attr_id_list))
            {
                foreach ($attr_id_list AS $key => $attr_id)
                {
                    $attr_value = $attr_value_list[$key];
                    // $attr_price = $_POST['attr_price_list'][$key];
                    // $attr_price = ($attr_price>=0) ? $attr_price : 0;
                    if (!empty($attr_value))
                    {
                        if (isset($goods_attr_list[$attr_id][$attr_value]))
                        {
                            // 如果原来有，标记为更新
                            $goods_attr_list[$attr_id][$attr_value]['sign'] = 'update';
                            // $goods_attr_list[$attr_id][$attr_value]['attr_price'] = $attr_price;
                        }
                        else
                        {
                            // 如果原来没有，标记为新增
                            $goods_attr_list[$attr_id][$attr_value]['sign'] = 'insert';
                            // $goods_attr_list[$attr_id][$attr_value]['attr_price'] = $attr_price;
                        }
                    }
                }
            }

            /* 插入、更新、删除数据 */
            $siteId = get_site_id();
            foreach ($goods_attr_list as $attr_id => $attr_value_list)
            {
                foreach ($attr_value_list as $attr_value => $info)
                {
                    if ($info['sign'] == 'insert')
                    {
                        $data = array(
                            'attr_id'    => $attr_id,
                            'goods_id'   => $goods_id,
                            'attr_value' => $attr_value,
                            'site_id'    => $siteId,
                        );
                        db('goods_attr')->insert($data);
                    }
                    elseif ($info['sign'] == 'update')
                    {

                    }
                    else
                    {
                        //删除商品属性
                        db('goods_attr')->delete($info['goods_attr_id']);

                        //删除商品属性对应的货品信息
                        // $sql = "DELETE FROM __PRODUCT__ WHERE goods_id = '$goods_id' and (goods_attr = '".$info['goods_attr_id']."' or goods_attr like '%|".$info['goods_attr_id']."' or goods_attr like '".$info['goods_attr_id']."|%' or goods_attr like '%|".$info['goods_attr_id']."|%')";
                        // M()->query($sql);

                        continue;
                    }
                    // $db->query($sql);
            
                }
            }
        }
    }
    
}
